<template>
<div class="login">
  <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-position="top" label-width="80px">
    <el-form-item label="手机号" prop="phone">
      <el-input v-model="ruleForm.phone"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input type="password" v-model="ruleForm.password"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit" :loading="isLoading">login</el-button>
    </el-form-item>
  </el-form>
</div>
</template>

<script lang="ts">
import Vue from 'vue'
import { Form } from 'element-ui'
import { login } from '@/serives/user'

export default Vue.extend({
  name: 'LoginIndex',
  data () {
    return {
      ruleForm: {
        phone: '18201288771',
        password: '111111'
      },
      isLoading: false,
      rules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请填写密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度应在 6 位到 20 位', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async onSubmit () {
      try {
        // 1 表单验证
        await (this.$refs.ruleForm as Form).validate()
        // 2 发送请求
        this.isLoading = true
        const { data } = await login(this.ruleForm)
        console.log(data)
        // 3 处理结果
        if (data.state !== 1) {
          this.$message.error(data.message)
        } else {
          this.$store.commit('setUser', data.content)
          // this.$router.push({
          //   name: 'home'
          // })
          this.$router.push(this.$route.query.redirect as string || '/')
          this.$message.success('登录成功!')
        }
      } catch (err) {
        console.log('登录失败!')
      }
      this.isLoading = false
    }
  }
})
</script>

<style scoped>
.login{
  display:flex;
  width:100%;
  height:100vh;
  justify-content:center;
  align-items:center;
}
.el-form{
  width:300px;
  background:#fff;
  padding:20px 30px;
  border-radius:10px;
}
.el-button{
  width:100%;
  text-align:center;
}
</style>
